package com.njtech.pet.service.impl;

import com.alibaba.fastjson.JSON;
import com.njtech.pet.constant.Constant;
import com.njtech.pet.dao.FriendDao;
import com.njtech.pet.dao.MessageDao;
import com.njtech.pet.dao.UserDao;
import com.njtech.pet.entity.Friend;
import com.njtech.pet.entity.Message;
import com.njtech.pet.entity.User;
import com.njtech.pet.service.MessageService;
import com.njtech.pet.vo.MessageShow;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Author:gm
 * Date:2020-03-22 20:27
 * Description:<描述>
 */
@Service
@Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
public class MessageServiceImpl implements MessageService {
    @Autowired
    UserDao userDao;
    @Autowired
    FriendDao friendDao;
    @Autowired
    MessageDao messageDao;
    /**
     * 插入一条记录
     * @param message 新纪录
     * @return 修改行数
     */
    @Override
    public int insert(Message message){
        return messageDao.insert(message);
    }

    /**
     * 修改一条记录的state状态
     * @param message 新纪录，封装了id和新状态
     * @return 修改行数
     */
    @Override
    public int updateMessageStateByMessageId(Message message){
        return messageDao.updateMessageStateByMessageId(message);
    }

    /**
     * 根据一对用户（2人）和起止日期查找聊天记录, sender和receiver是等价的参数
     * @param sender 发送消息的用户
     * @param receiver 接受消息的用户
     * @param beginDate 起日期，可NULL，日期格式 "yyyy-MM-dd HH:mm:ss"
     * @param endDate 止日期，可NULL，日期格式 "yyyy-MM-dd HH:mm:ss"
     * @return 记录集合
     */
    @Override
    public List<Message> selectByCoupleUsersBetweenDates(@Param("sender") User sender, @Param("receiver")User receiver, @Param("beginDate") String beginDate, @Param("endDate") String endDate){
        if(beginDate.equals("")||beginDate==null){
            beginDate=null;
        }
        if(endDate.equals("")||endDate==null){
            endDate=null;
        }
        return messageDao.selectByCoupleUsersBetweenDates(sender,receiver,beginDate,endDate);
    }


    /**
     * 消息列表显示
     * @param uid
     * @return
     */
    @Override
    public List<MessageShow> selectUnRead(Integer uid){
        User client = new User();
        client.setId(uid);

        List<MessageShow> messageShows = messageDao.selectReceiverMessageShow(client,"未读");
        System.out.println(messageShows);

        return messageShows;
    }

    /**
     * 查找一对用户的所有消息
     * @param sid  当前用户
     * @param rid  对方用户
     * @return     消息集合
     */
    @Override
    public List<Message> selectAll(Integer sid, Integer rid) {
        User user = userDao.selectByUserId(sid);
        User receiver = userDao.selectByUserId(rid);
        List<Message> messageList = messageDao.selectByCoupleUsersAndTypeAndStatesBetweenDates(user,receiver,null,null,null,null);
        System.out.println(messageList);
        return messageList;
    }

    /**
     * 查找当前用户的未读消息：包括好友消息和通讯信息
     * @param uid
     * @return
     */
    @Override
    public String longSearch(Integer uid){
        User user = new User();
        user.setId(uid);

        //找别人给自己的已发送
        List<Friend>list_01 = friendDao.selectByFriend(user, Constant.Friend.STATE_SENT.getValue(),null,null,"userName asc");
        System.out.println(list_01);
        System.out.println("已发送数目为："+list_01.size());

        //找别人给自己的已拒绝*
        List<Friend>list_02 = friendDao.selectByUser(user, Constant.Friend.STATE_REJECTED_UNREAD.getValue(), null, null, "friendName asc");
        System.out.println(list_02);
        System.out.println("已拒绝*数目："+list_02.size());

        //找别人给自己的未读消息
        List<MessageShow>messageShows = messageDao.selectReceiverMessageShow(user,"未读");
        System.out.println("meassageShow"+messageShows);
        int t = 0;
        for (MessageShow temp:
                messageShows) {
            if(temp.getUnreadCount()!=null) {
                t = t + temp.getUnreadCount();
            }
        }
        System.out.println(messageShows);
        System.out.println("未读消息的数目为："+t);
        int count = 0;
        count =list_01.size()+list_02.size()+t;

        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("好友请求的数目",list_01.size());
        resultMap.put("好友拒绝的数目",list_02.size());
        resultMap.put("未读消息数目",t);
        String json = JSON.toJSONString(resultMap);
        return json;
    }


    /**
     * 点击一个好友进入当前用户和好友的对话框时，将对方给自己的未读message的状态修改
     * @param uid   当前操作的用户id
     * @param rid  对方id
     * @return
     */
    @Override
    public String changeState(Integer uid,Integer rid){
        //获得对方给自己的未读消息集合
        User user01 = new User();
        user01.setId(rid);
        User user02 = new User();
        user02.setId(uid);

        List<Message> messageList = messageDao.selectByCoupleUsersAndTypeAndStatesBetweenDates(user01,user02,null,null,null,null);
        System.out.println(messageList);
        //修改状态
        for (Message temp:
                messageList) {
            if(temp.getState().equals("未读")) {
                temp.setState(Constant.Message.STATE_READ.getValue());
                messageDao.updateMessageStateByMessageId(temp);
            }
        }
        return "修改成功";
    }

    /**
     * 找A===》B的最近一条未读message
     * @param sid  发送方id
     * @param rid  接收方id
     * @return     message
     * （待考虑）
     */
    @Override
    public Message findAMessageByBoth(Integer sid,Integer rid){
        User sender = new User();
        sender.setId(rid);
        User receiver = new User();
        receiver.setId(sid);
        List<Message> messageShows = messageDao.selectByCoupleUsersBetweenDates(sender,receiver,null,null);
Message message = new Message();
        int size = messageShows.size();
        for (int i=size-1;i>=0;i--) {
            if(messageShows.get(i).getSender().getId().equals(sid)
            &&(messageShows.get(i).getReceiver().getId().equals(rid))
            &&(messageShows.get(i).getState().equals("未读"))) {
                message = messageShows.get(i);
                System.out.println("最新的A===》B的最近一条未读message："+message);
                break;
            }
        }
        return message;
    }
}
